package managers;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import utils.StackTracePrinter;


public class DBManager {

	private static final int DEFAULT_RETRY_COUNT = 5;
	private static Connection conn = null;

	private DBManager () {	
	}
	
	
	private static void connect() throws SQLException {
				int retryCount = DEFAULT_RETRY_COUNT;
				conn = null;
				do {
					try {
						System.out.println("Trying to connect... ("+retryCount+")");
						conn = DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=9a6b3df996");
						retryCount=0;
						System.out.println("Connected to DB!");
						return;
					} catch (SQLException e) {
							retryCount--;
					}
				} while (retryCount != 0);
				throw new SQLException("Connection to DB failed.");
			}
	
	public static Connection getConnection() throws SQLException {
		if (conn == null)
			connect();
		return conn;
	}
	
	
	public static void closeResources (Statement stmt, ResultSet rs) {
		try {
			if (rs!= null)
				rs.close();
			if (stmt!= null)
				stmt.close();
		} catch (SQLException e) {
			StackTracePrinter.print(e);
			System.err.println("Error while closing resources.");
		}
	}
	
	public static void closeConnection () {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				StackTracePrinter.print(e);
			}
		}
		conn = null;
	}
	
}
